import { notFound } from "next/navigation";
import { ReaderView } from "@/components/reader/reader-view";
import { getBookById } from "@/data/demo-books";

type ReaderPageProps = {
  params: Promise<{
    bookId: string;
  }>;
  searchParams?: Promise<{
    chapter?: string;
    width?: string;
    theme?: string;
    font?: string;
  }>;
};

export default async function ReaderPage({ params, searchParams }: ReaderPageProps) {
  const { bookId } = await params;
  const resolvedSearchParams = searchParams ? await searchParams : undefined;
  const book = getBookById(bookId);

  if (!book) {
    notFound();
  }

  const rawChapterIndex = Number(resolvedSearchParams?.chapter ?? "0");
  const chapterIndex =
    Number.isFinite(rawChapterIndex) && rawChapterIndex >= 0 && rawChapterIndex < book.chapters.length
      ? rawChapterIndex
      : 0;

  return (
    <ReaderView
      book={book}
      chapterIndex={chapterIndex}
      initialWidthKey={resolvedSearchParams?.width}
      initialThemeKey={resolvedSearchParams?.theme}
      initialFontKey={resolvedSearchParams?.font}
    />
  );
}
